<!--编辑字典-->
<script setup>
import { nextTick } from 'vue'
import useDialog from '@/hooks/use-dialog'
import { validate20WordsRequired, validate200Words } from '@/utils/form-validate'
import { ElMessage, ElMessageBox } from 'element-plus'
import { throttle } from 'lodash-es'
import useDelPop from '@/hooks/use-del-popover'
import { delParamsDictMockApi, listParamsByKeyMockApi, saveParamsMockApi } from '@/api/mock-js/system/params-api'

defineOptions({
  name: 'DialogParams'
})

const modelValue = defineModel({type: Boolean})

const emit = defineEmits(['on-close'])

const formData = reactive({
  tableData: []
})
const {formRef, title, preTitle, loadData, close, readClose} = useDialog(emit, formData, modelValue)

const rules = {
  paramValue: {required: true, trigger: 'blur', validator: validate20WordsRequired},
  paramValueName: {required: true, trigger: 'blur', validator: validate20WordsRequired},
  remarks: {trigger: 'blur', validator: validate200Words}
}
// 删除 hooks
const {delData, visibleDelPop, tempRef, showDelPop} = useDelPop()
const isEditing = ref(false)
const parentInfo = ref({
  paramKey: ''
})

/* 获取字典表
* @param paramKey 字典键
 */
const renderTable = async (paramKey) => {
  if ( !paramKey) {
    modelValue.value = false
    return
  }
  loadData.loading = true
  try {
    const res = await listParamsByKeyMockApi(paramKey)
    res.data.map(item => {
      item.isEditing = false
    })
    formData.tableData = res.data
  } catch (e) {
  } finally {
    loadData.loading = false
  }
}
// 新增行
const newRow = () => {
  if (isEditing.value) {
    ElMessage.warning('请先保存已修改的数据，再进行新增操作！')
    return
  }
  isEditing.value = true
  const _row = {
    isEditing: true,
    paramKey: parentInfo.value.paramKey,
    paramName: parentInfo.value.paramName,
    paramValue: '',
    paramType: 2,
    paramValueName: '',
    remarks: ''
  }
  formData.tableData.push(_row)
}
// 取消修改，还原数据
const cancel = async (scope) => {
  isEditing.value = false
  scope.row.isEditing = false
  await renderTable(parentInfo.value.paramKey)
}
// 删除行
const del = async (id) => {
  loadData.loading = true
  try {
    await delParamsDictMockApi(id)
    ElMessage.error('删除成功!')
    await renderTable(parentInfo.value.paramKey)
  } catch (e) {
  } finally {
    loadData.loading = false
  }
}
// 编辑行
const editRow = (scope) => {
  isEditing.value = true
  scope.row.isEditing = true
}
// 保存行
const save = throttle((row) => {
  formRef?.value.validate(valid => {
    if (valid) {
      ElMessageBox.confirm(`此操作将${row.id ? '修改' : '新增'}该行数据字典 , 是否继续?`, '保存提示').then(async () => {
        loadData.loading = true
        try {
          await saveParamsMockApi(row)
          ElMessage.success('保存成功!')
          await renderTable(parentInfo.value.paramKey)
        } catch (e) {
        }
      }).catch(async () => {
        await renderTable(parentInfo.value.paramKey)
      }).finally(() => {
        isEditing.value = false
        loadData.loading = false
      })
    }
  })
}, 1000)
onMounted(async () => {
  await nextTick()
  await renderTable(parentInfo.value.paramKey)
})
defineExpose({
  preTitle, title, formData, parentInfo
})
</script>
<template>
  <DialogForm
      class="dialog-dict-params"
      :model-value="modelValue"
      :title="`编辑系统字典-${parentInfo.paramName}(${parentInfo.paramKey})`"
      hide-flag
      align-center
      width="820px"
      :loading="loadData.loading"
      @on-save="save(saveParamsMockApi,'系统字典')"
      @on-close="readClose"
      @on-cancel="readClose"
  >
    <div class="font-right">
      <ElButton type="primary" class="mr-1" @click="newRow">新增</ElButton>
    </div>
    <ElForm ref="formRef" :model="formData" v-loading="loadData.loading" :rules="rules" size="large" label-width="0">
      <ElTable :data="formData.tableData">
        <ElTableColumn label="ID" type="index" width="70" align="center"/>
        <ElTableColumn width="160" label="字典值" #default="scope">
          <ElFormItem v-if="scope.row.isEditing" :prop="`tableData.${scope.$index}.paramValue`"
                      :rules="rules.paramValue">
            <ElInput v-model="scope.row.paramValue"/>
          </ElFormItem>
          <span v-else>{{ scope.row.paramValue }}</span>
        </ElTableColumn>
        <ElTableColumn width="160" label="字典名" #default="scope">
          <ElFormItem v-if="scope.row.isEditing" :prop="`tableData.${scope.$index}.paramValueName`"
                      :rules="rules.paramValueName">
            <ElInput v-model="scope.row.paramValueName"/>
          </ElFormItem>
          <span v-else>{{ scope.row.paramValueName }}</span>
        </ElTableColumn>
        <ElTableColumn min-width="200" label="备注" #default="scope">
          <ElFormItem v-if="scope.row.isEditing" :prop="`tableData.${scope.$index}.remarks`"
                      :rules="rules.remarks">
            <ElInput v-model="scope.row.remarks"/>
          </ElFormItem>
          <span v-else>{{ scope.row.remarks }}</span>
        </ElTableColumn>
        <ElTableColumn label="操作" width="200px">
          <template v-slot="scope">
            <template v-if="scope.row.isEditing">
              <ElFormItem>
                <ElButton @click="cancel(scope)" size="default">取消</ElButton>
                <ElButton
                    type="primary" size="default"
                    v-if="scope.row.isEditing" @click="save(scope.row)">保存
                </ElButton>
              </ElFormItem>
            </template>
            <template v-else>
              <template v-if="!isEditing">
                <ElButton v-permission="['sys:params:del']" size="default"
                          @click="e=>showDelPop(e,scope.row,'系统字典')">
                  删除
                </ElButton>
                <ElButton
                    type="primary" plain size="default"
                    @click="editRow(scope)">编辑
                </ElButton>
              </template>
            </template>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElForm>
    <!--  删除popover start -->
    <DeletePopover v-if="visibleDelPop"
                   :temp-ref="tempRef"
                   v-model:del-info="delData"
                   v-model="visibleDelPop"
                   @on-submit="del(delData.id)"/>
    <!--  删除popover end -->
    <template #dialogFooter>
      <!-- 添加此slot可隐藏保存按钮 -->
    </template>
  </DialogForm>
</template>

<style lang="scss">
.dialog-dict-params {
  .el-dialog__body {
    padding-top: 0;
  }
}
</style>
